﻿using FreeSql;
using Microsoft.Data.SqlClient;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Reflection;

namespace DataUp
{
    internal static class ParameterExtend
    {
        /// <summary>
        /// 对象转换为DbParameter(反射)
        /// </summary>
        /// <param name="Parameter"></param>
        /// <returns></returns>
        internal static IEnumerable<DbParameter> ChangeSqlParameter(this object Parameter, DataType dataType)
        {
            List<DbParameter> DbParameters = new List<DbParameter>();
            FieldInfo[] objFields = Parameter.GetType().GetFields();
            foreach (FieldInfo fieldInfo in objFields)
            {
                var para = CreateDbParameter(fieldInfo.Name, fieldInfo.GetValue(Parameter), dataType);
                DbParameters.Add(para);
            }
            PropertyInfo[] propertyInfos = Parameter.GetType().GetProperties();
            foreach (PropertyInfo prop in propertyInfos)
            {
                var para = CreateDbParameter(prop.Name, prop.GetValue(Parameter), dataType);
                DbParameters.Add(para);
            }
            return DbParameters;
        }


        /// <summary>
        /// 创建DbParameter
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ParameterName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        internal static DbParameter CreateDbParameter(string ParameterName, object value, DataType dataType)
        {
            switch (dataType)
            {
                case DataType.MySql:
                    return new MySqlParameter(ParameterName, value);
                case DataType.SqlServer:
                    return new SqlParameter(ParameterName, value);
                default:
                    throw new Exception("暂不支持此数据库");
            }
        }
    }
}
